//
//  AddDrugReminderViewController.m
//  安好
//
//  Created by lianchuang on 14-11-29.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "AddDrugReminderViewController.h"
#import "AddDrugReminderCell.h"
#import "AddDrugTimeReminderCell.h"
//点击药品-名称-push到write页面
#import "WriteFamilyViewController.h"
//“剂量”选中器
#import "DrugCountPickerView.h"
//“时间”选择器
#import "MyHourMinutePickerView.h"
//展示页面
#import "ShowDrugDetialViewController.h"
//闹钟提醒
#import "RemindDrugManager.h"

#define addCellLineColor [UIColor colorWithRed:221/255.0 green:221/255.0 blue:221/255.0 alpha:1];

#define IPhone6Plus ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size) : NO)

@interface AddDrugReminderViewController ()<UITableViewDataSource,UITableViewDelegate,WriteFamilyViewControllerDelegate>

@property(nonatomic,strong)UITableView * tableView;

//药品名称
@property(nonatomic,copy)NSString * drugName;
//药品剂量
@property(nonatomic,copy)NSString * doseCountString;
//药品时间字符串
@property(nonatomic,copy)NSString * timeString;


//保存时间数组和“添加提醒时间”
@property(nonatomic,strong)NSMutableArray * secondDataArray;
//保存时间数组
@property(nonatomic,strong)NSMutableArray * timeDataArray;
//第一段“药品”“剂量”
@property(nonatomic,strong)AddDrugReminderCell * firstSelectCell;
//第二段“时间”cell
@property(nonatomic,strong)AddDrugTimeReminderCell * secondSelectCell;
//“剂量”选择器
@property(nonatomic,strong)DrugCountPickerView * drugAndDosePickerView;
//“时间”选择器
@property(nonatomic,strong)MyHourMinutePickerView *timeReminderPickerView;
/**
 *  半透明的图片 -- 当点击升起pickerView的时候 这个也sheng起来
 */
@property(nonatomic,strong)UIView * alphaView;


@end

@implementation AddDrugReminderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self makeNavBar];
    [self loadData];
    [self makeTableView];
    
}
-(void)viewDidAppear:(BOOL)animated
{
    [self makeTimeReminderView];
    [self makeDrugAndDosePickerView];
    
}
#pragma mark - 导航条
-(void)makeNavBar
{
    self.navigationItem.title = @"添加用药提醒";//添加用药提醒
    // 返回按钮图片
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backBtnClicked)];
    backBtnImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnImg;
    
    // 完成
    UIBarButtonItem *OkBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_完成.png"] style:UIBarButtonItemStylePlain target:self action:@selector(OkButtonclicked)];
    OkBtnImg.tintColor = [UIColor whiteColor];
    OkBtnImg.tag = 100;
    self.navigationItem.rightBarButtonItem = OkBtnImg;
}
//返回展示页面
-(void)backBtnClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}
//“完成”--push到展示页面
//需要增加上传数据，传值
-(void)OkButtonclicked
{
    [self AFNetReuqestFor_ADD_FamilyDrugReminder];
    
}

#pragma mark - AFNet-新增家人用药提醒
-(void)AFNetReuqestFor_ADD_FamilyDrugReminder
{
    
    if (self.drugName.length == 0) {
        [self showCustomHudSingleLine:@"请添加药品名称"];
        return ;
    }
    if (self.doseCountString.length == 0) {
        [self showCustomHudSingleLine:@"请添加剂量"];
        return ;
    }
    if (self.timeDataArray.count==0 ) {
        [self showCustomHudSingleLine:@"请添加提醒时间"];
        return ;
    }
    //把时间数组转成时间字符串，以“,”隔开
    NSMutableString * timeString = [NSMutableString stringWithCapacity:0];
    for (NSInteger i = 0; i < self.timeDataArray.count; i++) {
        [timeString appendString:self.timeDataArray[i]];
        if (i != self.timeDataArray.count-1) {
            [timeString appendString:@","];
        }
    }
    self.timeString = timeString;
    
    NSString * postURL = [NSString stringWithFormat:@"%@user/drugAdd/",kBaseURL];
    NSDictionary * parameters = @{@"platform":kPlatform,@"version":kVersion,@"fid":self.familyInfoDic[@"fid"],@"drug":self.drugName,@"dose":self.doseCountString,@"time":self.timeString};
    [self showActionView];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self hiddenActionView];
        MyNSLog("网络请求成功");
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            alertContent([responseObject objectForKey:@"msg"]);
            MyNSLog("有问题");
        }else
        {
            MyNSLog("11111111111成功添加 %@,%@",responseObject,[responseObject objectForKey:@"msg"]);
            //获取到提醒id
            NSString * reminderID = [[responseObject objectForKey:@"data"] objectForKey:@"id"];
            //网络添加成功之后--把所有时间都开启闹钟提醒，把时间存入本地
            NSUserDefaults * timeUser = [NSUserDefaults standardUserDefaults];
            NSArray * timeOpenArray = [self.timeString componentsSeparatedByString:@","];
            MyNSLog("%@", timeOpenArray);
            [timeUser setObject:timeOpenArray forKey:[NSString stringWithFormat:@"%@%@%@",self.familyInfoDic[@"uid"],self.familyInfoDic[@"fid"],reminderID]];
            [timeUser synchronize];
            
            //开启时间存入本地之后--把闹钟通知开启--默认都是开启的
            //循环把所有时间都开启并add到本地通知
            for (NSInteger i = 0; i < timeOpenArray.count;i++ ) {
                /**
                 *  用户uid,家人fid,某个药品提醒reminderId,该药品时间time这4个值拼成时间闹钟的提醒key
                 *  key = @"uid,fid,reminderId,time"
                 */
#pragma mark 本地推送闹钟提醒的 key = @"uid,fid,reminderId,time"
                
                NSString * RemindIDcolockTimeKey = [NSString stringWithFormat:@"%@,%@,%@,%@",self.familyInfoDic[@"uid"],self.familyInfoDic[@"fid"],reminderID,timeOpenArray[i]];
                
                //key确定之后把--药品剂量，药品名称，该药品下所有的体系那个时间传进去
                
                
                
                [[RemindDrugManager shareInstance] addNewRemindWithUserName:@"" andMedicineName:@"" andMedicineDosage:@"" andNewTime:timeOpenArray[i] andMessage:@"" andUserID:@"2" andRemindID:RemindIDcolockTimeKey andFamilyInfoDic:self.familyInfoDic];
            }

            //成功之后push到展示页面
            ShowDrugDetialViewController * showDetial = [[ShowDrugDetialViewController alloc] init];
            showDetial.drugName = self.drugName;
            showDetial.doseCountString = self.doseCountString;
            showDetial.timeString = self.timeString;
            
            NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithDictionary:self.familyInfoDic];
            [dic setValue:reminderID forKey:@"reminderID"];
            showDetial.familyInfoDic = dic;
            [self.navigationController pushViewController:showDetial animated:YES];
            
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        MyNSLog("添加用药提醒失败");
        [self hiddenActionView];
    }];
}


#pragma mark - 加载数据
-(void)loadData
{
    self.secondDataArray = [NSMutableArray arrayWithCapacity:0];
    self.timeDataArray = [NSMutableArray arrayWithCapacity:0];
    NSArray * timeSubArray = [self.timeString componentsSeparatedByString:@","];
    for (NSString * time in timeSubArray) {
        [self.timeDataArray addObject:time];
    }
    [self.secondDataArray addObject:self.timeDataArray];
    [self.secondDataArray addObject:@"添加提醒时间"];
    
    
}
#pragma mark - tableView--的创建
-(void)makeTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-iOS7TopMargin) style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //隐藏横向和竖向的滑条
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    //设置cell之间分割线为None
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
#pragma mark - tableView的代理方法
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (IPhone6Plus) {
        return 53;
    }else{
        return 44;
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (IPhone6Plus) {
        return 12;
    }else{
        return 10;
    }
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 2;
    }else
    {
        return self.timeDataArray.count + 1;
    }
    
}
#pragma mark - ----UITableView的代理方法：Cell-加载
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        AddDrugReminderCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];
        if (cell == nil) {
            if (IPhone6Plus) {
                cell = [[[NSBundle mainBundle] loadNibNamed:@"AddDrugReminderCell" owner:self options:nil] lastObject];
            }else{
                cell = [[[NSBundle mainBundle] loadNibNamed:@"AddDrugReminderCell" owner:self options:nil] firstObject];
            }
        }
        //设置线条
        cell.topLineView.backgroundColor = addCellLineColor
        cell.topLineView.height = 0.35;
        cell.jumpImgView.right = kScreenWidth-15;
        if (IPhone6Plus) {
            cell.jumpImgView.right = kScreenWidth-20;
        }
        //添加内容
        if (indexPath.row == 0) {
            cell.itemLable.text = @"药品";
            cell.itemDetialLable.text = self.drugName;
            [cell.itemImgView setImage:[UIImage imageNamed:@"药品.png"]];
            cell.topLineView.width = kScreenWidth;
            
        }else
        {
            cell.topLineView.frame = CGRectMake(55, 0, kScreenWidth-55, 0.3);
            cell.bottomLineView.frame = CGRectMake(0,cell.height-0.5, kScreenWidth, 0.5);
             cell.bottomLineView.backgroundColor = addCellLineColor
            [cell.itemImgView setImage:[UIImage imageNamed:@"单位.png"]];
            cell.itemLable.text = @"剂量";
            cell.itemDetialLable.text = self.doseCountString;
            
            if (IPhone6Plus) {
                cell.topLineView.left = 65;
            }
            
            
        }
        cell.itemDetialLable.right = cell.jumpImgView.left-5;
        
        return cell;
        
    }
    else
    {
        AddDrugTimeReminderCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TIME"];
        if (cell == nil) {
            if (IPhone6Plus) {
                cell = [[[NSBundle mainBundle] loadNibNamed:@"AddDrugTimeReminderCell" owner:self options:nil] lastObject];
            }else{
                cell = [[[NSBundle mainBundle] loadNibNamed:@"AddDrugTimeReminderCell" owner:self options:nil] firstObject];
            }
        }
        //对线条的设置
        cell.bottomLineView.frame = CGRectMake(0, cell.height-0.7, kScreenWidth, 0.3);

        //顶部线条
        if (indexPath.row ==0) {
            cell.topLineView.backgroundColor = addCellLineColor
            cell.topLineView.frame = CGRectMake(0, 0, kScreenWidth, 0.3);
            //只有第一行有图片
            [cell.timeItemImgView setImage:[UIImage imageNamed:@"时间.png"]];
        }else
        {
            cell.timeItemImgView.hidden = YES;
        }
        //底部线条
        if (self.timeDataArray.count == indexPath.row ) {
            cell.bottomLineView.backgroundColor = addCellLineColor
            cell.bottomLineView.frame = CGRectMake(55, cell.height-0.5, kScreenWidth-55, 0.5);
            if (IPhone6Plus) {
                cell.bottomLineView.left = 65;
            }
        }
        
        
        //先判断时间数组是否已经删除完--全部删除的话那么此时度二段只有1行，
        if (self.timeDataArray.count == 0) {
            cell.getTimeLable.text = @"时间";
            cell.deleteTimeButton.tag = indexPath.row+1000;
            cell.deleteTimeButton.hidden = YES;
            [cell.addTimeImgView setImage:[UIImage imageNamed:@"加号.png"]];
            cell.addTimeImgView.top = (cell.height - cell.addTimeImgView.height)/2.0;
            cell.addTimeImgView.right = kScreenWidth-15;
            cell.bottomLineView.frame = CGRectMake(0, cell.height-0.5, kScreenWidth, 0.5);
            if (IPhone6Plus) {
                cell.addTimeImgView.right = kScreenWidth-20;
            }
        }
        else//还有时间显示
        {
            //时间数组不为0，最后一行“添加时间”
            if (indexPath.row ==self.timeDataArray.count)
            {
                cell.addTimeImgView.hidden = NO;
                cell.deleteTimeButton.hidden = YES;
                [cell.addTimeImgView setImage:[UIImage imageNamed:@"加号.png"]];
                cell.addTimeImgView.right = kScreenWidth - 15;
                cell.getTimeLable.text = @"添加提醒时间";
                cell.bottomLineView.frame = CGRectMake(0, cell.height-0.5, kScreenWidth, 0.5);
                if (IPhone6Plus) {
                    cell.addTimeImgView.right = kScreenWidth - 22;
                }
            }
            else{
            
                cell.getTimeLable.text = self.timeDataArray[indexPath.row];
                cell.addTimeImgView.hidden = YES;
                //每一个时间cell---后面的“删除”按钮
                cell.deleteTimeButton.hidden = NO;
                cell.deleteTimeButton.right = kScreenWidth-15;
                if (IPhone6Plus) {
                    cell.deleteTimeButton.right = kScreenWidth-22;

                }
                cell.deleteTimeButton.tag = indexPath.row+1000;
                [cell.deleteTimeButton addTarget:self action:@selector(deleteTheCellReminderTime:) forControlEvents:UIControlEventTouchUpInside];
                cell.bottomLineView.backgroundColor =addCellLineColor;
                cell.bottomLineView.frame = CGRectMake(55, cell.height-0.5, kScreenWidth-55, 0.5);
                if (IPhone6Plus) {
                    cell.bottomLineView.left = 65;
                }
            }
            
        }
        
        return cell;
    }
    
}

#pragma mark --时间cell---后面的“删除”按钮触发方法
-(void)deleteTheCellReminderTime:(UIButton *)deleteBtn
{
    //把该行cell上的时间从timeDataArray中移除
    [self.timeDataArray removeObjectAtIndex:deleteBtn.tag-1000];
    
    //刷新table
    [self.tableView reloadData];
    
}

#pragma mark - ---UITableView的代理方法：选中末一行
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    //第一段---“药品”“剂量”
    if (indexPath.section == 0) {
        self.firstSelectCell = (AddDrugReminderCell *)[self.tableView cellForRowAtIndexPath:indexPath];
        
        if (indexPath.row == 0)//“药品”push到下一个页面
        {
            MyNSLog("选中---“药品”");
            WriteFamilyViewController *editDrugName = [[WriteFamilyViewController alloc] init];
            editDrugName.delegate = self;
            editDrugName.navBarTitle = @"请添加药品名称";
            editDrugName.textFieldPlaceholder = @"请添加药品名称";
            editDrugName.textString = self.firstSelectCell.itemDetialLable.text;
            [self.navigationController pushViewController:editDrugName animated:YES];
        }
        if (indexPath.row == 1)//“剂量”
        {
            MyNSLog("选中--“剂量”");
            [self makeAlphaView];
            [self.view bringSubviewToFront:self.drugAndDosePickerView];
            //弹出 剂量pickerView
            [UIView animateWithDuration:0.35 animations:^{
                self.drugAndDosePickerView.frame = CGRectMake(0, kScreenHeight-iOS7TopMargin-216, kScreenWidth, 216);
                self.alphaView.alpha = 0.35;
            }];
        }
    }
    //第二段----时间
    if (indexPath.section == 1) {
        MyNSLog("选中--某一个时间");
        self.secondSelectCell = (AddDrugTimeReminderCell *)[self.tableView cellForRowAtIndexPath:indexPath];;
        //弹出 时间pickerView
        [self makeAlphaView];
        [self.view bringSubviewToFront:self.timeReminderPickerView];
        [UIView animateWithDuration:0.35 animations:^{
            self.timeReminderPickerView.frame = CGRectMake(0, kScreenHeight-iOS7TopMargin-216, kScreenWidth, 216);
            self.alphaView.alpha = 0.35;
        }];
    }
}
#pragma mark --- 药品名称添加的代理方法
-(void)reloadTableViewSelectedCellPlaceholeder:(NSString *)placeholder
{
    //获取药品名字--添加到itemDetialLable上
    self.firstSelectCell.itemDetialLable.text = placeholder;
    //把编辑好的药品名字重新赋值给drugName
    self.drugName = placeholder;
}
#pragma mark - 药品计量选择器
-(void)makeDrugAndDosePickerView
{
    self.drugAndDosePickerView = [[DrugCountPickerView alloc] initWithFrame:CGRectMake(0, kScreenHeight-iOS7TopMargin, kScreenWidth, 216)];
    [self.view addSubview:self.drugAndDosePickerView];
    
    [self.drugAndDosePickerView.cancleButton addTarget:self action:@selector(drugCancleBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.drugAndDosePickerView.sureButton addTarget:self action:@selector(drugSureBtnClicked) forControlEvents:UIControlEventTouchUpInside];
}
//“取消”按钮
-(void)drugCancleBtnClicked
{
    [self recoverPickerViewDown];
}
//确定 获取剂量
-(void)drugSureBtnClicked
{
    self.firstSelectCell.itemDetialLable.text = self.drugAndDosePickerView.getDrugDose;
    //获取药品剂量
    self.doseCountString = self.drugAndDosePickerView.getDrugDose;
    [self recoverPickerViewDown];
}
#pragma mark - 时间选择器picker
-(void)makeTimeReminderView
{
    self.timeReminderPickerView = [[MyHourMinutePickerView alloc] initWithFrame:CGRectMake(0, kScreenHeight-iOS7TopMargin, kScreenWidth, 216)];
    [self.timeReminderPickerView.cancelButton addTarget:self action:@selector(TimecancelButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.timeReminderPickerView.sureButton addTarget:self action:@selector(TimesureButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.timeReminderPickerView];
    [self.view bringSubviewToFront:self.timeReminderPickerView];
    
}
//"取消"--按钮
-(void)TimecancelButtonClicked
{
    
    [self recoverPickerViewDown];
}
//确定-选中提醒时间
-(void)TimesureButtonClicked
{
    //选中时间先判断是否和时间数组中的其他时间相同
    for (NSString *time in self.timeDataArray)
    {
        if ([time isEqualToString:[self.timeReminderPickerView getDateString]]) {
            [self showCustomHudSingleLine:@"时间不可重复"];
            return;
        }
    }
    NSIndexPath * indexPath = [self.tableView indexPathForCell:self.secondSelectCell];
    //时间数组为空--选中时间后把他添加进时间数组
    if (self.timeDataArray.count == 0) {
        [self.timeDataArray addObject:[self.timeReminderPickerView getDateString]];
    }
    else//如果不为空
    {
        //判断选中的时最后一行(添加新的时间)
        if (indexPath.row ==self.timeDataArray.count)
        {
            [self.timeDataArray addObject:[self.timeReminderPickerView getDateString]];
        }
        else//选中的时原来的时间--修改原来的
        {
            [self.timeDataArray replaceObjectAtIndex:indexPath.row withObject:[self.timeReminderPickerView getDateString]];
        }
        
    }
    NSArray * sortArr = [self.timeDataArray  sortedArrayUsingSelector:@selector(compare:)];
    [self.timeDataArray removeAllObjects];
    for (NSString * time in sortArr) {
        [self.timeDataArray addObject:time];
    }
    

    [self recoverPickerViewDown];
    //做完之后 刷新页面
    [self.tableView reloadData];
    
}

#pragma mark - 恢复“剂量”“时间”选择器下去
-(void)recoverPickerViewDown
{
    [UIView animateWithDuration:0.35 animations:^{
        self.drugAndDosePickerView.frame = CGRectMake(0, kScreenHeight-iOS7TopMargin, kScreenWidth, 216);
        self.timeReminderPickerView.frame = CGRectMake(0, kScreenHeight-iOS7TopMargin, kScreenWidth, 216);
        self.alphaView.alpha = 0;
    } completion:^(BOOL finished) {
        [self.alphaView removeFromSuperview];
    }];
}

#pragma mark - 创建半透明的view
-(void)makeAlphaView
{
    self.alphaView = [[UIView alloc] initWithFrame:CGRectMake(0,0, kScreenWidth, kScreenHeight-iOS7TopMargin)];
    self.alphaView.backgroundColor = [UIColor blackColor];
    self.alphaView.alpha = 0;
    [self.view addSubview:self.alphaView];
    //给这个半透明的View添加一个手势
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(alphaViewTapClicked:)];
    [self.alphaView addGestureRecognizer:tap];
}
-(void)alphaViewTapClicked:(UITapGestureRecognizer*)tap{
    
    [self recoverPickerViewDown];
    
    
}


@end
